<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 订单物料需求模型
 */
class OrderMaterial extends Model
{
    // 表名
    protected $name = 'scanwork_order_material';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'purchase_status_text',
        'stock_status_text'
    ];
    
    /**
     * 采购状态列表
     */
    public function getPurchaseStatusList()
    {
        return [
            '0' => __('待采购'),
            '1' => __('已下单'),
            '2' => __('已到货')
        ];
    }

    /**
     * 采购状态文本
     */
    public function getPurchaseStatusTextAttr($value, $data)
    {
        $value = isset($data['purchase_status']) ? $data['purchase_status'] : 0;
        $list = $this->getPurchaseStatusList();
        $text = isset($list[$value]) ? $list[$value] : '';
        
        $colorMap = [
            '0' => 'default',
            '1' => 'warning',
            '2' => 'success'
        ];
        $color = isset($colorMap[$value]) ? $colorMap[$value] : 'default';
        
        return '<span class="label label-' . $color . '">' . $text . '</span>';
    }

    /**
     * 库存状态列表
     */
    public function getStockStatusList()
    {
        return [
            '0' => __('待准备'),
            '1' => __('已备料')
        ];
    }

    /**
     * 库存状态文本
     */
    public function getStockStatusTextAttr($value, $data)
    {
        $value = isset($data['stock_status']) ? $data['stock_status'] : 0;
        $list = $this->getStockStatusList();
        $text = isset($list[$value]) ? $list[$value] : '';
        
        $color = $value == 1 ? 'success' : 'default';
        
        return '<span class="label label-' . $color . '">' . $text . '</span>';
    }

    /**
     * 关联订单
     */
    public function order()
    {
        return $this->belongsTo('Order', 'order_id', 'id');
    }

    /**
     * 关联物料
     */
    public function material()
    {
        return $this->belongsTo('Material', 'material_id', 'id');
    }

    /**
     * 关联供应商
     */
    public function supplier()
    {
        return $this->belongsTo('Supplier', 'supplier_id', 'id');
    }

    /**
     * 检查是否缺料
     */
    public function isShortage()
    {
        if (!$this->material) {
            return true;
        }
        
        return $this->required_quantity > $this->material->stock;
    }

    /**
     * 获取缺货数量
     */
    public function getShortageQuantityAttr($value, $data)
    {
        if (!$this->material) {
            return isset($data['required_quantity']) ? $data['required_quantity'] : 0;
        }
        
        $shortage = $this->required_quantity - $this->material->stock;
        return $shortage > 0 ? $shortage : 0;
    }
}

